﻿jQuery.extend({
    openPage: function (name, url, text, width, height, id, showCloseButton) {
        if (!id || id == '') {
            id = "dialog_div";
        }
        if ($('#' + id).length == 0) {
            $('body').append('<div id="' + id + '"></div>');
        }
        $('#' + id).window({
            content: '<iframe scrolling="yes" frameborder="0"  src="' + url + '" width="100%" height="100%"></iframe>',
            width: width,
            height: height,
            modal: true,
            title: text,
            iconCls: 'icon-edit',
            closable: true,
            collapsible: false, minimizable: false, maximizable: false,
            resizable: false,
            loadingMessage: 'processing......'

        });
        $('#' + id).window('open');
    },
    closePage: function (id) {
        var _id = id || 'dialog_div';
        $('#' + _id).window('close');
    },

    showhelp: function (url) {
        var help = $("<div></div>").addClass('help').bind("click", function () {
            $.openPage('', url, 'help', '90%', '90%');
        });
        $("body").append(help);
    },
    /**
    * 说明：对select控件进行数据绑定
    * 参数：obj select对象
    *       opts 数据列表
    *       text 数据对象的文本的属性名
    *       value 数据对象的值属性名
    */
    bindSelect: function (obj, opts, text, value) {
        if (!obj || !opts) return;
        if (obj.jquery)
            obj = obj[0];
        for (var q = 0; q < opts.length; q++) {
            var opt = new Option(opts[q][text || 'text'], opts[q][value || 'value'] || '');
            if (obj.options)
                obj.options.add(opt);
            if (opts[q].selected == true || opts[q].selected == "true") {
                opt.selected = true;
            }
        }
    },
    cookie: function (name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || { path: '/' };
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            var path = options.path ? '; path=' + options.path : '';
            var domain = options.domain ? '; domain=' + options.domain : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    },
    cookieName: "tadong.sessionid",
    cookieFuncName: "cookieFuncName",
    cookieClear: function () {
        $.cookie($.cookieName, null);
    },
    cookieSet: function (v) {
        try {
            (top.$ || $).cookie($.cookieName, v);
        }
        catch (err) {
            $.cookie($.cookieName, v);
        }
    },
    cookieCheck: function () {
        try {
            if ((top.$ || $).oemCookie() == "" || (top.$ || $).oemCookie() == null)
                window.location = "/login.html?href=" + escape(window.location);
        }
        catch (err) {
            if ($.oemCookie() == "" || $.oemCookie() == null)
                window.location = "/login.html?href=" + escape(window.location);
        }
    },
    oemCookie: function () {
        var cookie;
        try {
            cookie = (top.$ || $).cookie($.cookieName);
        }
        catch (err) {
            cookie = $.cookie($.cookieName);
        }
        if (!cookie) {
            cookie = $.getPara($.cookieName);
        }
        return cookie;
    },
    cookieUrl: function (url) {
        var cookie;
        cookie = $.cookie($.cookieName);
        if (!cookie) {
            if ($.getPara($.cookieName) != "") {
                cookie = $.getPara($.cookieName);
                $.cookieSet(cookie);
            }
            else
                return url;
        }
        if (url.indexOf("?") == -1)
            url = url + "?";
        else
            url = url + "&";
        url = url + $.cookieName + "=" + cookie;
        url = url + '&t=' + new Date().getTime();
        return url;
    },
    getPara: function (name, url) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        if (url) {
            if (url.indexOf("?") != -1)
                url = url.split("?")[1];
        } else if (window.location.search.length > 1) {
            url = decodeURI(window.location.search.substr(1));
        } else {
            return '';
        }
        var r = url.match(reg);
        if (r != null) return unescape(r[2]); return '';
    },
    ajaxHandler: function (ajaxObj) {
        var g = {
            // 加载进度条
            loading: function (_msg) {
                var loadimg = "<span class='ajax_msg'></span>";
                if (!ajaxObj.loading || !ajaxObj.loading.id)
                    ajaxObj.loading = { id: "ajaxmsg", message: "handle..." };
                var msg = "";
                if (_msg && _msg != "")
                    msg = _msg;
                else
                    msg = loadimg + ajaxObj.loading.message;
                if ($("#" + ajaxObj.loading.id).length == 0) {
                    $("body").append("<div id='" + ajaxObj.loading.id + "'></div>");
                    $('#' + ajaxObj.loading.id).html(msg);

                    $('#' + ajaxObj.loading.id).css({ position: 'fixed', top: '10px', left: '50%', margin: '0 0 0 -200px', padding: '4px 15px', background: '#f2a001', color: '#fff', cursor: 'pointer' });
                    var _msgwidth = Math.round($('#' + ajaxObj.loading.id).width() / 2);
                    $('#' + ajaxObj.loading.id).css({ margin: "0 0 0 -" + _msgwidth + 'px' });
                    $('#' + ajaxObj.loading.id).show();
                    $('#' + ajaxObj.loading.id).bind('click', function () { $('#' + ajaxObj.loading.id).fadeTo("normal", 0.5).slideUp("normal"); });
                } else {

                    $('#' + ajaxObj.loading.id).html(msg);
                    if ($('#' + ajaxObj.loading.id).css("position") == "fixed") {
                        var _msgwidth = Math.round($('#' + ajaxObj.loading.id).width() / 2);
                        $('#' + ajaxObj.loading.id).css({ margin: "0 0 0 -" + _msgwidth + 'px' });
                    }
                    $('#' + ajaxObj.loading.id).show();
                }
            },
            // 隐藏进度条
            hideload: function () {
                if (!ajaxObj.loading || !ajaxObj.loading.id) return;
                $('#' + ajaxObj.loading.id).hide();
            },
            // 成功返回处理
            success: function (data, textStatus) {
                try {
                    if (data == undefined || data == '') {
                        g.hideload();
                        return;
                    }
                    var result = data;
                    if (result instanceof Array)
                        result = result[0];
                    if (result.State == 0) {
                        g.hideload();
                        if (ajaxObj.success) ajaxObj.success(result.Data, (result.Page || null), (result.DataDifferTime || null));
                    } else {
                        g.loading(result.ErrMsg ? result.ErrMsg : result.Message);
                        if (ajaxObj.failure) ajaxObj.failure(result.ErrMsg ? result.ErrMsg : result.Message);
                    }
                } catch (e) {

                    g.loading(e);

                }
            },
            // 失败返回处理
            error: function (xmlhttp, textStatus, errorThrown, errFrom) {
                if (errorThrown && errorThrown.message && errorThrown.message.indexOf(' was not called') > 0) {
                    xmlhttp.status = '403';
                }
                if (xmlhttp && xmlhttp.status == '200') {
                    // 有空跟踪
                } else if (xmlhttp && xmlhttp.status == '403') {
                    if (top != self) {
                        $.openPage('login', App_Config.CurrentUrl + '/login.html?type=checklogin&errFrom=' + errFrom, 'please login', 600, 353, '', false);
                    } else {
                        location.href = App_Config.CurrentUrl + "/login.html?href=" + escape(location.href);
                    }
                } else {
                    //alert("对不起，网络连接出错，请联系管理员！原因:" + errorThrown + "-" + textStatus);
                    //alert($.toJSON(xmlhttp));
                }
            },
            // 提交动作
            submit: function () {
                var r = {};
                var param = null;
                if (ajaxObj.model) {
                    if (typeof ajaxObj.model == "function") {
                        param = ajaxObj.model();
                    } else {
                        param = ajaxObj.model;
                    }
                }
                if (ajaxObj.check && !ajaxObj.check(param)) {
                    g.hideload();
                    return;
                }
                if (ajaxObj.urlType) {
                    r.Type = ajaxObj.urlType;
                    r.Param = param;
                    if (ajaxObj.Page) r.Page = ajaxObj.Page;
                    if (ajaxObj.ColOrder) r.ColOrder = ajaxObj.ColOrder;

                } else {
                    r = param;
                }

                var dataType = ajaxObj.dataType || "json";
                var url = ajaxObj.url || App_Config.TadongUrl + "/AjaxMappingHandler.aspx";
                url = $.cookieUrl(url);
                var option = {
                    type: 'post',
                    dataType: dataType,
                    url: url,
                    data: "data=" + $.toJSON(r).replace(/\+/g, '%2B'),
                    success: g.success,

                    error: g.error
                };
                if (url.indexOf("http") == 0) {
                    option.dataType = "jsonp";
                    option.jsonp = "jsonpcallback";
                }

                $.ajax(option);
            }
        };
        g.loading();
        g.submit();
    },
    toJSON: function (o) {
        var f = function (n) {
            return n < 10 ? '0' + n : n;
        },
		escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
		quote = function (value) {
		    escapable.lastIndex = 0;
		    return escapable.test(value) ?
				'"' + value.replace(escapable, function (a) {
				    var c = meta[a];
				    return typeof c === 'string' ? c :
						'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
				}) + '"' :
				'"' + value + '"';
		};
        if (o === null) return 'null';
        var type = typeof o;
        if (type === 'undefined') return undefined;
        if (type === 'string') return quote(o);
        if (type === 'number' || type === 'boolean') return '' + o;
        if (type === 'object') {
            if (typeof o.toJSON === 'function') {
                return $.toJSON(o.toJSON());
            }
            if (o.constructor === Date) {
                return isFinite(this.valueOf()) ?
                   this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z' : null;
            }
            var pairs = [];
            if (o.constructor === Array) {
                for (var i = 0, l = o.length; i < l; i++) {
                    pairs.push($.toJSON(o[i]) || 'null');
                }
                return '[' + pairs.join(',') + ']';
            }
            var name, val;
            for (var k in o) {
                type = typeof k;
                if (type === 'number') {
                    name = '"' + k + '"';
                } else if (type === 'string') {
                    name = quote(k);
                } else {
                    continue;
                }
                type = typeof o[k];
                if (type === 'function' || type === 'undefined') {
                    continue;
                }
                val = $.toJSON(o[k]);
                pairs.push(name + ':' + val);
            }
            return '{' + pairs.join(',') + '}';
        }
    }
});
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, start) {
        for (var i = (start || 0), j = this.length; i < j; i++) {
            if (this[i] === obj) { return i; }
        }
        return -1;
    }
}